package com.bigerdranch.android.geoquiz;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 主要完成用户回答问题操作
 */
public class GeoquizActivity extends AppCompatActivity {

    // 实例变量声明
    private Button mTrueButton;
    private Button mFalseButton;
    private Button mNextButton;
    private Button mPrevButton;
    private Button mCheatButton;
    private TextView mQuestionTextView;

    private int mCurrentIdx = 0;
    private boolean mIsCheater;// 记录用户是否偷看了答案

    private Question[] mQuestionBank;
    private static final String KEY_IDX = "CurrIdx";
    private static final String KEY_FLAG = "Currflagx";
    private static final String TAG = "GeoQuizTag";

    private static final int REQUEST_CODE_CHEAT = 0;

    // 答题的状态值
    private int[] flag;// 记录答题状态
    private static final int CORRECT_ANSWER = 1;// 回答正确
    private static final int ERROR_ANSWER = 2;// 回答正错误
    private static final int NO_RESPONSE = 3;// 查看了答案
    public static final String EXTRA_ANSWER_QUESTION_ANSWER =
            "com.bignerdranch.android.geoquiz.question_answer";
    public static final String EXTRA_ANSWER_COUNT_INFO =
            "com.bignerdranch.android.geoquiz.true_false_acc";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_geoquiz);

        // 设置第一个问题下标，默认为0
        if (savedInstanceState != null) {
            mCurrentIdx = savedInstanceState.getInt(KEY_IDX, 0);
            flag = savedInstanceState.getIntArray(KEY_FLAG);
        }

        // 初始化问题
        Resources res = this.getResources();
        String[] questions = res.getStringArray(R.array.question);
        String[] answers = res.getStringArray(R.array.answer);
        int length = questions.length;
        mQuestionBank = new Question[length];
        for (int i = 0; i < length; i++) {
            mQuestionBank[i] = new Question(questions[i], answers[i]);
        }
        // 初始化记录数组
        flag = new int[length];

        // 获取视图组件
        mTrueButton = findViewById(R.id.true_button);
        mFalseButton = findViewById(R.id.false_button);
        mQuestionTextView = findViewById(R.id.question_text_view);
        mNextButton = findViewById(R.id.next_button);
        mPrevButton = findViewById(R.id.prev_button);
        mCheatButton = findViewById(R.id.cheat_button);

        // 设置问题文本框
        mQuestionTextView.setText(mQuestionBank[mCurrentIdx].getQuestionString());

        // 设置下一个按钮
        mNextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(true);
                if (flag[mCurrentIdx] == 0) {
                    mTrueButton.setEnabled(true);
                    mFalseButton.setEnabled(true);
                } else {
                    mTrueButton.setEnabled(false);
                    mFalseButton.setEnabled(false);
                }
            }
        });

        // 设置上一个按钮
        mPrevButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(false);
                if (flag[mCurrentIdx] == 0) {
                    mTrueButton.setEnabled(true);
                    mFalseButton.setEnabled(true);
                } else {
                    mTrueButton.setEnabled(false);
                    mFalseButton.setEnabled(false);
                }
            }
        });

        // 设置错误按钮
        mFalseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkQuestion(false);
                updateQuestion(true);
            }
        });

        // 设置正确按钮
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkQuestion(true);
                updateQuestion(true);
            }
        });

        // 启用查看答案的按钮
        mCheatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取出题目和答案
                String answer = mQuestionBank[mCurrentIdx].getAnswerString();
                String question = mQuestionBank[mCurrentIdx].getQuestionString();
                //创建QuizActivity类和AnswerActivity类的连接信封
//                Intent intentCheat = new Intent(GeoquizActivity.this, CheatActivity.class);
                Intent intentCheat = CheatActivity.newIntent(GeoquizActivity.this,question + "\n答案为: " + answer);
                //在intent连接信封中附加消息
//                intentCheat.putExtra(EXTRA_ANSWER_QUESTION_ANSWER, question + "\n答案为: " + answer);
                startActivityForResult(intentCheat,REQUEST_CODE_CHEAT);
            }
        });
    }

    /**
     * 跳转问题
     * @param isDown true 跳转到下一个，false跳转到上一个
     */
    private void updateQuestion(boolean isDown) {
        if (isDown){
            if (mCurrentIdx < mQuestionBank.length - 1) {
                mCurrentIdx = (mCurrentIdx + 1) % mQuestionBank.length;
                mIsCheater = false;
                mQuestionTextView.setText(mQuestionBank[mCurrentIdx].getQuestionString());
            }
        }else {
            if (mCurrentIdx > 0) {
                mCurrentIdx = (mCurrentIdx - 1) % mQuestionBank.length;
                mQuestionTextView.setText(mQuestionBank[mCurrentIdx].getQuestionString());
            }
        }
    }

    /**
     * 检查答案
     */
    private void checkQuestion(boolean userPressedTrue) {
        boolean answerIsTrue = Boolean.parseBoolean(mQuestionBank[mCurrentIdx].getAnswerString());
        // 基于mIsCheater改变toast消息
        if (mIsCheater) {// 告诉用户已经查看了答案
            Toast.makeText(GeoquizActivity.this,
                    R.string.judgment_toast,
                    Toast.LENGTH_SHORT).show();
            flag[mCurrentIdx] = NO_RESPONSE;
        } else {// 如果没有查看答案，且回答正确
            if (answerIsTrue == userPressedTrue) {
                Toast.makeText(GeoquizActivity.this,
                        R.string.correct_toast,
                        Toast.LENGTH_SHORT).show();
                flag[mCurrentIdx] = CORRECT_ANSWER;
            } else {// 回答错误
                Toast.makeText(GeoquizActivity.this,
                        R.string.incorrect_toast,
                        Toast.LENGTH_SHORT).show();
                flag[mCurrentIdx] = ERROR_ANSWER;
            }
        }
        // 答题完毕，开始统计
        if (mCurrentIdx == mQuestionBank.length - 1) {
            statisticalAnswers(flag);
        }
    }

    /**
     * 统计用户的答题情况
     */
    private void statisticalAnswers(int[] flag){
        int trueNum = 0;
        int falseNum = 0;
        int noNum = 0;
        for (int j : flag) {
            if (j == CORRECT_ANSWER) {
                trueNum++;
            } else if (j == ERROR_ANSWER) {
                falseNum++;
            } else {
                noNum++;
            }
        }
        // 输出 正确，错误和未作答的个数
        @SuppressLint("DefaultLocale") String resultInfo = String.format(
                "正确的个数是：%d\n错误的个数为：%d\n未作答的个数为：%d\n 正确率为：%.2f",
                trueNum, falseNum, noNum, trueNum / (mQuestionBank.length * 1.0)
        );
        // Toast.makeText(this, resultInfo, Toast.LENGTH_LONG).show();
        // 与显示页面通信
        Intent intentExit = new Intent(GeoquizActivity.this, ExitActivity.class);
        intentExit.putExtra(EXTRA_ANSWER_COUNT_INFO, resultInfo);
        startActivity(intentExit);
        finish();
    }

    /**
     * 横竖屏保存状态：主要是保存用户的回答到哪一个题
     */
    @Override
    protected void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
//        Log.d(TAG, "onSaveInstanceState");
        savedInstanceState.putInt(KEY_IDX, mCurrentIdx);
        savedInstanceState.putIntArray(KEY_FLAG,flag);
    }

    /**
     * 在进行界面跳转的时候，需要获取跳转之后的界面的数据和状态信息
     * 处理返回结果：就是用mIsCheater记录用户是否偷看了答案
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("--------------");
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_CHEAT) {
            if (data == null) {
                return;
            }
            mIsCheater = CheatActivity.wasAnswerShown(data);
            System.out.println("mischeater: "+mIsCheater);
        }
    }
    // ============================================== 日志模块 =================================
    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "onStart() ing……");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop() ing……");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy() ing……");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause() ing……");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume() ing……");
    }
}